//
//  CameraMameHomePageViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-10-2.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "CameraMameHomePageViewController.h"
#import "RTLabel.h"

#import "MJPhoto.h"
#import "MJPhotoBrowser.h"
#import "UIImageView+MJWebCache.h"

@interface CameraMameHomePageViewController ()
{
    int allCount;
    int page;
    
    BOOL isfirst;
    
    UILabel * testLabel;
}
@end

@implementation CameraMameHomePageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.contentView.hidden = YES;
    self.navigationBarView.hidden = YES;
    self.view.backgroundColor = self.navigationBarView.backgroundColor;
    page = 1;
    dataArray = [[NSMutableArray alloc] init];
    
    [self initHeaderView];
    [self requestCameraMameInfo];
    [self requestCameraMaNCommentInfo];
}

-(void)initHeaderView
{
    float adjustHeight =20.0;
    if (IOS7) {
        adjustHeight = 0;
    }
    
    
    //整个HeaderBaseView
    baseHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 180+150+90+5+35)];
    baseHeaderView.backgroundColor = UIColorFromRGB(0xfffefa);
    baseHeaderView.userInteractionEnabled = YES;
//    [self.view addSubview:baseHeaderView];
    
    //背景
    UIImageView *headerBgIV = [[UIImageView alloc]init];
    headerBgIV.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, 180);
    headerBgIV.image = [UIImage imageNamed:@"mycenterbg"];
    [baseHeaderView addSubview:headerBgIV];
    
    //头像iv
    UIView  *headerCircle = [[UIView alloc]init];
    headerCircle.frame =  CGRectMake((UI_SCREEN_WIDTH - 78)/2-1, 65+adjustHeight-2.5, 80, 80);
    headerCircle.layer.masksToBounds = YES;
    headerCircle.layer.opacity = 0.5;
    headerCircle.layer.cornerRadius = 40.0f;
    headerCircle.backgroundColor = UIColorFromRGB(0xe5ccd3);
    [headerBgIV addSubview:headerCircle];
    //名字label
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake((UI_SCREEN_WIDTH - 160)/2, height_y(headerCircle), 160, 30)];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.text = self.cameraManName;
    [headerBgIV addSubview:nameLabel];
    //摄影师头像
    UIImageView *headerIV = [[UIImageView alloc]init];
    headerIV.frame =CGRectMake((UI_SCREEN_WIDTH - 75)/2, 65+adjustHeight, 75, 75);
    headerIV.layer.masksToBounds = YES;
    headerIV.layer.cornerRadius = 37.5f;
    headerIV.image = self.cameraHeaderImage;
    [headerBgIV addSubview:headerIV];
    //我的照片
    UILabel *myPhotoString = [[UILabel alloc]initWithFrame:CGRectMake(15,height_y(headerBgIV)+8, 80, 30)];
    myPhotoString.text = @"我的照片";
    myPhotoString.textColor = UIColorFromRGB(0xb6b6b4);
    [baseHeaderView addSubview:myPhotoString];
    
    //表格布局
    layoutTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT) style:UITableViewStylePlain];
    layoutTableView.delegate =self;
    layoutTableView.dataSource = self;
//    layoutTableView.tableHeaderView = baseHeaderView;
    layoutTableView.backgroundColor = UIColorFromRGB(0xfffefa);
    layoutTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [layoutTableView addFooterWithTarget:self action:@selector(footerRefreshFuncion)];
    [self.view addSubview:layoutTableView];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(5, adjustHeight + 15, 44, 44);
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setBackgroundImage:[UIImage imageNamed:@"backBtn_image2"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [baseHeaderView addSubview:backButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIdentifer = @"commentCell";
    
    CommentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (!cell) {
        cell = [[CommentsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
    }
    cell.delegate = self;
    cell.dataDict = [dataArray objectAtIndex:indexPath.row];

    return cell;
}

#pragma  tableview 代理方
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!testLabel) {
        testLabel = [[UILabel alloc] init];
        testLabel.numberOfLines = 0;
        testLabel.font = [UIFont systemFontOfSize:15];
    }
    
    testLabel.frame = CGRectMake(0, 0, 300, 23);
    testLabel.text = [[dataArray objectAtIndex:indexPath.row] valueForKey:@"ReviewContent"];
    [testLabel sizeToFit];
    if ([[[dataArray objectAtIndex:indexPath.row] valueForKey:@"ReviewPhoto"] count]){
        return 10+50+10+testLabel.bounds.size.height+20+70+20;
    }
    
    return 10+50+10+testLabel.bounds.size.height+20;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
-(void)backButtonPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)footerRefreshFuncion
{
    if (1) {
        page++;
        [self requestCameraMaNCommentInfo];
    }else{
        if (1) {
            layoutTableView.footerRefreshingText = @"没有更多数据...";
            [self performSelector:@selector(delayToEndRefreshLoading) withObject:nil afterDelay:.5f];
        }
    }
}

-(void)delayToEndRefreshLoading
{
    [layoutTableView footerEndRefreshing];
    layoutTableView.footerRefreshingText = @"正在加载数据";
}

#pragma mark
#pragma mark 点击图片浏览大图
-(void)imageViewClick:(UITapGestureRecognizer *)tap
{
    DDLOG_CURRENT_METHOD;
    UIImageView * iv =(UIImageView *)tap.view;
    NSMutableArray * imgarr = [[NSMutableArray alloc] init];
    for (UIImageView * view in baseHeaderView.subviews){
        if ([view isKindOfClass:[UIImageView class]]){
            if (view.tag==10000||view.tag==10001||view.tag==10002){
                [imgarr addObject:view];
            }
        }
    }
    NSArray * photoArray = [[NSArray alloc] initWithArray:[cameraInfo objectForKey:@"photo"]];
    if (ARRAY_IS_NOT_EMPTY(photoArray)){
        int count = photoArray.count;
        NSMutableArray * photos = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++) {
            NSString *url = photoArray[i];
            MJPhoto * photo = [[MJPhoto alloc] init];
            photo.url = [NSURL URLWithString:url]; // 图片路径
            photo.srcImageView = [imgarr objectAtIndex:i];
            [photos addObject:photo];
        }
        
        // 2.显示相册
        MJPhotoBrowser * browser = [[MJPhotoBrowser alloc] init];
        browser.currentPhotoIndex = iv.tag-10000;
        browser.photos = photos; // 设置所有的图片
        [browser show];
    }
    
}

#pragma mark
#pragma mark CommentsTableViewCellDelegate
-(void)chooseImageView:(UIImageView *)iv andIvArray:(NSArray *)ivArray andImageUrlArray:(NSArray *)mImageUrlArray
{
    if (ARRAY_IS_NOT_EMPTY(mImageUrlArray)){
        int count = mImageUrlArray.count;
        NSMutableArray * photos = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++) {
            NSString *url = mImageUrlArray[i];
            MJPhoto * photo = [[MJPhoto alloc] init];
            photo.url = [NSURL URLWithString:url]; // 图片路径
            photo.srcImageView = [ivArray objectAtIndex:i];
            [photos addObject:photo];
        }
        
        // 2.显示相册
        MJPhotoBrowser * browser = [[MJPhotoBrowser alloc] init];
        browser.currentPhotoIndex = iv.tag-1000;
        browser.photos = photos; // 设置所有的图片
        [browser show];
    }
}

-(void)requestCameraMameInfo
{

    if(![XDTools NetworkReachable]){
        self.navigationBarView.hidden = NO;
        layoutTableView.hidden = YES;
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    NSDictionary *requestDic = @{@"EmplID":self.cameraManId};
    ASIHTTPRequest *request = [XDTools postRequestWithDict:requestDic API:API_CAMERAMAN_HOME_INFO];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        NSDictionary *resultDic = [XDTools JSonFromString:[mrequest responseString]];
        DDLOG(@"res....%@",resultDic);
        if ([[resultDic objectForKey:@"status"] intValue]==1) {
            cameraInfo = [[NSDictionary alloc]initWithDictionary:[resultDic objectForKey:@"data"]];
            [self reloadCameraManImage];
        }else{
            
            [XDTools showErrorTips:[resultDic objectForKey:@"msg"] toView:self.view];
        }

    }];
    [request setFailedBlock:^{
        self.navigationBarView.hidden = NO;
        layoutTableView.hidden = YES;
        [XDTools hideProgress:self.contentView];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request setTimeOutSeconds:12];
    [request startAsynchronous];

}
-(void)reloadCameraManImage
{
    float gapDistance = (UI_SCREEN_WIDTH-3*90)/4.0f;
    for (int i=0; i <[[cameraInfo objectForKey:@"photo"] count];i++ ) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(gapDistance*(i+1)+i*90, 65+75+30+10+45, 90, 90)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[[cameraInfo objectForKey:@"photo"] objectAtIndex:i]] placeholderImage:[UIImage imageNamed:@"red"]];
        imageView.userInteractionEnabled = YES;
        [baseHeaderView addSubview:imageView];
        imageView.tag = 10000+i;
        
        UITapGestureRecognizer * tapp = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewClick:)];
        [imageView addGestureRecognizer:tapp];
    }
    //自我介绍
    UIView *myIntro = [[UIView alloc]initWithFrame:CGRectMake(0, 180+45+90+15, UI_SCREEN_WIDTH, 90)];
    myIntro.backgroundColor = [UIColor whiteColor];
    UIView *lineUp =[[UIView alloc]initWithFrame:CGRectMake(0, .5f, UI_SCREEN_WIDTH, .5f)];
    lineUp.backgroundColor = UIColorFromRGB(0xd6d6d6);
    [myIntro addSubview:lineUp];
   
    UILabel *myIntroString = [[UILabel alloc]initWithFrame:CGRectMake(15,5, 80, 30)];
    myIntroString.text = @"自我介绍";
    myIntroString.textColor = UIColorFromRGB(0xb6b6b4);
    [myIntro addSubview:myIntroString];
    
    RTLabel *introString = [[RTLabel alloc]init];
    introString.frame = CGRectMake(myIntroString.frame.origin.x, height_y(myIntroString)+10, 295, 60);
    introString.tag = 1111;
    introString.textColor=UIColorFromRGB(0x6f6254);
    if (IS_NOT_EMPTY([cameraInfo objectForKey:@"Summary"])) {
        introString.text = [cameraInfo objectForKey:@"Summary"];
    }else{
        introString.text = @"这个摄影师太懒，什么也没有留下....";
    }
    
    introString.lineBreakMode = RTTextLineBreakModeWordWrapping;
    introString.font = [UIFont systemFontOfSize:16.0f];
    CGSize adjustSize = [introString optimumSize];
    float increstHeight = adjustSize.height - 30;  //请求完数据然后 算一下高度，然后重新布局.
    introString.frame = CGRectMake(myIntroString.frame.origin.x, height_y(myIntroString)+5, 295, increstHeight+30);
    myIntro.frame = CGRectMake(myIntro.frame.origin.x, myIntro.frame.origin.y, myIntro.frame.size.width, myIntro.frame.size.height + increstHeight);
    UIView *lineDown =[[UIView alloc]initWithFrame:CGRectMake(0,myIntro.frame.size.height - .5f, UI_SCREEN_WIDTH, .5f)];
    lineDown.backgroundColor = UIColorFromRGB(0xd6d6d6);
    [myIntro addSubview:lineDown];
    [myIntro addSubview:introString];
    [baseHeaderView addSubview: myIntro];
    
    //顾客评价
    UIView *commentTittle = [[UIView alloc]initWithFrame:CGRectMake(0, height_y(myIntro)+5, UI_SCREEN_WIDTH, 35)];
    commentTittle.tag = 2222;
    commentTittle.backgroundColor = [UIColor whiteColor];
    UIView *lineCommentUp =[[UIView alloc]initWithFrame:CGRectMake(0, .5f, UI_SCREEN_WIDTH, .5f)];
    lineCommentUp.backgroundColor = UIColorFromRGB(0xd6d6d6);
    [commentTittle addSubview:lineCommentUp];
    UIView *lineCommentDown =[[UIView alloc]initWithFrame:CGRectMake(0,commentTittle.frame.size.height - .5f, UI_SCREEN_WIDTH, .5f)];
    lineCommentDown.backgroundColor = UIColorFromRGB(0xd6d6d6);
    [commentTittle addSubview:lineCommentDown];
    UILabel *CommetIntroString = [[UILabel alloc]initWithFrame:CGRectMake(15,0, 80, 30)];
    CommetIntroString.text = @"顾客评价";
    CommetIntroString.textColor = UIColorFromRGB(0xb6b6b4);
    [commentTittle addSubview:CommetIntroString];
    [baseHeaderView addSubview:commentTittle];
     baseHeaderView.frame = CGRectMake(baseHeaderView.frame.origin.x, baseHeaderView.frame.origin.y, baseHeaderView.frame.size.width, baseHeaderView.frame.size.height + increstHeight);
    layoutTableView.tableHeaderView = baseHeaderView;
}

#pragma mark
#pragma mark 摄影师评论
-(void)requestCameraMaNCommentInfo
{
    if (![XDTools NetworkReachable]){
        
        page = page==1?(1):(page-1);
        
        [XDTools showTips:brokenNetwork toView:self.view];
        [layoutTableView footerEndRefreshing];
        return;
    }
    
    if (self.cameraManId == nil) {
        return;
    }
    
    //page 页码 pageSize 每页数据条数  EmplID  摄影师id
    NSDictionary * parms = @{@"page":[NSString stringWithFormat:@"%d",page],
                             @"pageSize":@"10",
                             @"EmplID":self.cameraManId};
    
    ASIHTTPRequest * request = [XDTools postRequestWithDict:parms API:API_GETCOMMENTS];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        
        [layoutTableView footerEndRefreshing];
        
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            allCount = [[tmpDict valueForKey:@"Count"] intValue];
            if (page == 1){
                [dataArray removeAllObjects];
            }
            if (!(ARRAY_IS_NOT_EMPTY(tmpDict[@"data"][@"List"]))){
//                [XDTools showTips:tmpDict[@"msg"] toView:self.view];
                page = page==1?(1):(page-1);
                [layoutTableView reloadData];
                return;
            }
            [dataArray addObjectsFromArray:tmpDict[@"data"][@"List"]];
            [layoutTableView reloadData];
            
        }else{
            if (page == 1){
//                [XDTools showTips:@"暂无评论" toView:self.view];

            }else{
                [XDTools showTips:@"没有更多评论" toView:self.view];
            }
            page = page==1?(1):(page-1);
        }
    }];
    [request setFailedBlock:^{
        
        page = page==1?(1):(page-1);
        
        [layoutTableView footerEndRefreshing];
        
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    
    [request startAsynchronous];
    
    if (isfirst){
        [XDTools showProgress:self.contentView];
        isfirst = NO;
    }
    
}




@end
